<template>
   <div>
 <van-nav-bar
    title="注册账号"
    left-text="返回"
    left-arrow
    @click-left='$router.back()'
    />
       <van-form>
           <van-cell-group>
               <van-field
               clearable
                  v-model="user.mobile"
                  required
                  label="手机号"
                  placeholder="请输入手机号"
                  :rules="[
                  { required: true },
                  { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式错误！' },
        ]"
               />

               <van-field
                  clearable
                  v-model="user.password"
                  required
                  type="password"
                  label="密码"
                  placeholder="请输入密码"
                  :rules="password"

               />
               <van-field
                  clearable
                  v-model="user.repassword"
                  required
                  type="password"
                  label="确认密码"
                  placeholder="请再次输入密码"
                  :rules="password"
               />
           </van-cell-group>
       </van-form>
       <div style="margin: 16px">
           <van-button round block type="info" native-type="submit" @click="onsubmit">注册</van-button>
       </div>
   </div>
</template>

<script>
import { Toast } from 'vant'
import { register } from '@/api/user'
export default {
  data () {
    return {
      user: {
        mobile: null,
        password: null,
        repassword: null
      },
      password: [
        { required: true, message: '密码不能为空！' },
        { pattern: /^\d{6,12}$/, message: '密码长度要在6~12位！' }]
    }
  },
  methods: {
    onConfirm (value) {
      this.value = value
      this.showPicker = false
    },
    async onsubmit () {
      if (this.user.password !== this.user.repassword) {
        Toast('密码输入两次不一致！')
      } else {
        try {
          const res = await register(this.user)
          if (res.status === 400) {
            Toast.fail('注册失败')
            return Promise.reject(res.message)
          }
          Toast.success('注册成功')
          this.$router.push('/login')
        } catch (err) {
          Toast.fail(err)
          return false
        }
      }
    }
  }
}
</script>

<style scoped>
    .icon-back{
        position: absolute;
        left: 2px;
        top:15px
    }
</style>
